package com.hzhc.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.common.FileExcelUtil;
import com.hzhc.dto.UserDto;
import com.hzhc.entity.*;
import com.hzhc.enumBean.DdEnum;
import com.hzhc.enumBean.FyEnum;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.enumBean.WorkCarEnum;
import com.hzhc.mapper.*;
import com.hzhc.service.*;
import com.hzhc.utils.*;
import com.hzhc.vo.*;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 班列下集装箱详情 服务实现类
 * </p>
 *
 * @author 1
 * @since 2024-05-30
 */
@Service
@RequiredArgsConstructor
public class TrainPlanDetailServiceImpl extends ServiceImpl<TrainPlanDetailMapper, TrainPlanDetail> implements TrainPlanDetailService {

    private final CntrInfoMapper infoMapper;
    private final CntrInfoService infoService;
    private final CntrLogService logService;
    private final SysUserMapper userMapper;
    private final CntrLogMapper logMapper;
    private final TrainPlanMapper planMapper;
    private final CntrSizeMapper cntrSizeMapper;
    private final CntrTypeMapper cntrTypeMapper;

    private final ChargeConfigServiceImpl configService;
    private final ChargeConfigService chargeConfigService;
    private final ChargeContractMapper chargeContractMapper;
    private final CntrChargeDetailService cntrChargeDetailService;
    private final ChargeItemService chargeItemService;
    private final CompanyInfoMapper companyInfoMapper;
    private final YwOrderMapper orderMapper;
    private final YwOrderCntrMapper cntrMapper;
    private final VehicleReservationMapper reservationMapper;
    private final ProductNameMapper productNameMapper;
    private final SysMsgNotifyService notifyService;
    private final UserMemberMapper memberMapper;
    private final DeclareCarMapper declareCarMapper;
    private final TrainPlanZcdetailMapper trainPlanZcdetailMapper;

    @Override
    public ResultUtil<T> saveDetailMsg(TrainPlanDetail detail) {
//
//        List<TrainPlanDetail> trainPlanDetails = baseMapper.selectList(new QueryWrapper<TrainPlanDetail>()
//                .eq("disable", 0).in("cntr_no", detail.getCntrNoList()));
//        if(trainPlanDetails.size()==3){
//
//        }


        SysUser user = userMapper.selectById(detail.getUserId());
        //先删除Detail表中的箱子信息
//        LambdaUpdateWrapper<TrainPlanDetail> wrapper = new LambdaUpdateWrapper<>();
//        wrapper.eq(TrainPlanDetail::getPlanId,detail.getPlanId())
//                .eq(TrainPlanDetail::getTallyFlag,0)//未理货的箱子
//                .set(TrainPlanDetail::getDisable,1);
//        boolean b = update(wrapper);

        //再新增(
        int insert = 0;
        List<String> cntrNoList = detail.getCntrNoList();
        if (cntrNoList==null || cntrNoList.size()==0){
            return ResultUtil.ok();//没有选择任何箱子
        }
        //分组时间戳
        long millis = System.currentTimeMillis();
        for (String cntrNo : cntrNoList) {

            //校验是否已经绑定数据
            LambdaUpdateWrapper<TrainPlanDetail> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(TrainPlanDetail::getPlanId,detail.getPlanId()).eq(TrainPlanDetail::getDisable,0)
                    .eq(TrainPlanDetail::getCntrNo,cntrNo);
            int num = count(wrapper);
            if(num>0){
                return ResultUtil.build(400,"该箱子已经绑定过了！");
            }

            //cntrinfo 发运箱动态信息
            CntrInfo cntrInfo = infoMapper.selectById(cntrNo);
            cntrInfo.setCntrWorkRemark(FyEnum.YPF.getName());
            cntrInfo.setCntrWorkRemarkB(null);
            infoMapper.updateById(cntrInfo);
            //cntrlog 发运箱动态信息
            CntrLog log = new CntrLog();
            BeanUtils.copyProperties(cntrInfo,log);
            log.setCreatetime(LocalDateTime.now());
            log.setAccesspath("PC");
            logMapper.insert(log);
            //从业务cntr表获取专用线
            String zyx = cntrMapper.getZyxByCntrNoAndOrderNo(cntrNo,detail.getOrderNo());
            BeanUtils.copyProperties(cntrInfo,detail);
            //班列下集装箱详情的车牌号是装车理货的车皮号,不是箱子带来的车牌号
            detail.setCarNo(null);
            detail.setCreatetime(LocalDateTime.now());
            detail.setUserName(user.getRealname());
            detail.setAccesspath("PC");
            detail.setArea(cntrInfo.getArea());
            detail.setBay(cntrInfo.getBay());
            detail.setGroupId(String.valueOf(millis));//分组时间戳id
            detail.setLhWeight(cntrInfo.getLhWeight());//装车出场 理货\
            if(cntrInfo.getCompanyId()!=null){
                detail.setCompanyId(cntrInfo.getCompanyId().intValue());//货主 /客户id
            }
            detail.setLineOrYard(zyx);
            insert = baseMapper.insert(detail);

        }
        if (insert==0){
            return ResultUtil.fail();
        }
        return ResultUtil.ok();
    }

    @Override
    public List<TrainPlanDetailVo> getTrainPlanDetailList( TrainPlanDetailVo vo) {
        if (vo.getTrainPlanNo()!=null && !"".equals(vo.getTrainPlanNo())){
            LambdaQueryWrapper<TrainPlan> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TrainPlan::getDisable,0)
                            .eq(TrainPlan::getTrainPlanNo,vo.getTrainPlanNo());
            TrainPlan one = planMapper.selectOne(wrapper);
            vo.setPlanId(one.getId());
        }
        List<TrainPlanDetailVo> iPage = baseMapper.getTrainPlanDetailList(vo);
        List<TrainPlanDetailVo> voList = iPage;

        for (TrainPlanDetailVo detailVo : voList) {
            detailVo.setShipVia(cntrMapper.getShipViaByCntrNo(detailVo.getCntrNo(),detailVo.getOrderNo()));//详情展示发运方式
        }
        return voList;
    }

    @Override
    public Integer checkDetailExist(Long id) {
        return baseMapper.getTrainDetailCount(id);
    }

    @Override
    public List<TrainPlanDetailVo> getAllTrainPlanDetail(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        IPage<TrainPlanDetailVo> iPage = baseMapper.getAllTrainPlanDetail(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> carTally(TrainPlanDetailVo vo) {
        if (vo.getBay()!=null && vo.getBay()!="" && !vo.getBay().contains("区")){
            //判断该箱子 上面是否有箱子
            if (!(vo.getBay().matches(".*[\u4e00-\u9fa5]+.*")) && upCntrCheck(vo.getBay())){
                return ResultUtil.build(400, "贝位"+vo.getBay()+"上面存在箱子,请检查");
            }
        }

        CntrInfo one = infoMapper.selectOne(Wrappers.<CntrInfo>lambdaQuery()
                .eq(CntrInfo::getCntrNo, vo.getCntrNo()));

        if (one == null) {
            return ResultUtil.build(400, "集装箱不存在");
        }

        if (one.getStatus() != 0) {
            return ResultUtil.build(400, "该箱子不在场");
        }
        //特殊区域箱子
        if (vo.getBay().contains("区")){
            LambdaQueryWrapper<TrainPlanDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TrainPlanDetail::getCntrNo,vo.getCntrNo())
                    .eq(TrainPlanDetail::getDisable,0)
                    .eq(TrainPlanDetail::getTallyFlag,0);
            int num = count(wrapper);

            if (num==0){
                return ResultUtil.build(400, "该箱子还未绑定班列！");
            }

            wrapper.eq(TrainPlanDetail::getPlanId,vo.getPlanId());
            TrainPlanDetail detail = baseMapper.selectOne(wrapper);
            if (detail==null){
                return ResultUtil.build(400, "该箱子绑定的不是当前选择的班列！");
            }else {
                vo.setId(detail.getId());
            }
        }

        //寻找有没有 同车号的箱子 进行分组绑定
        List<TrainPlanDetail> trainPlanDetails = baseMapper.selectList(new QueryWrapper<TrainPlanDetail>().eq("plan_id", vo.getPlanId())
                .eq("train_number", vo.getTrainNumber()).eq("disable",0));
        if(trainPlanDetails.size()>0){
            if(trainPlanDetails.size()>=2){
                return ResultUtil.build(400, "无法编组3个及以上的箱子");
            }else {
                TrainPlanDetail trainPlanDetail = trainPlanDetails.get(0);
                if (trainPlanDetail.getCntrSize().startsWith("40") && one.getCntrSize().startsWith("40")) {
                    return ResultUtil.build(400, "两个箱子只能是一个 40 尺和一个 20 尺，或两个 20 尺");
                }
            }
        }

        //1.修改detail表 理货状态
        TrainPlanDetail detail = getById(vo.getId());
        if (detail.getTallyFlag()==1){
            return ResultUtil.build(400, "该箱子已被理货");
        }

        //分组时间戳 寻找相同 车号的数据 赋值分组id
        detail.setTallyFlag(1);
        detail.setTrainNumber(vo.getTrainNumber());//(铁皮号)车号
        detail.setZxTime(LocalDateTime.now());//理货时间
        detail.setTallyUserId(vo.getUserId());
        detail.setTallyMemberId(vo.getMemberId());
        detail.setTallyUserName(vo.getUserName());

        //1.根据箱号 找业务order_no  --   业务清单cntr表
//        YwOrderCntr cntr = cntrMapper.getYwCntrByCntrNo(detail.getCntrNo());

        if(vo.getOrderNo() != null && !"".equals(vo.getOrderNo())){//非手动增加的在场箱（业务进来的在场箱子）
            //根据在场箱子的委托号  找到业务
            YwOrderVo order = orderMapper.getYwOrderByOrderNo(vo.getOrderNo());
            if (order != null ){
                //更新业务下该箱号的车皮号
                LambdaQueryWrapper<YwOrderCntr> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(YwOrderCntr::getOrderNo,order.getOrderNo())
                        .eq(YwOrderCntr::getCntrNo,vo.getCntrNo())
                        .eq(YwOrderCntr::getDisable,0)
                        .eq(YwOrderCntr::getTallyState,10);

                YwOrderCntr orderCntr = cntrMapper.selectOne(wrapper1);
                if(orderCntr!=null){
                    orderCntr.setTruckNo(vo.getTrainNumber());//车皮号
                    orderCntr.setZcTallyFlag(1);//已装车
                    orderCntr.setZcTime(LocalDateTime.now());//装车时间
                    orderCntr.setZcUser(vo.getUserId()==null?vo.getMemberId().intValue():vo.getUserId().intValue());
                    cntrMapper.updateById(orderCntr);
                }
            }

        }

        //2.cntr_info
        CntrInfo cntrInfo = infoMapper.getCntrInfoById(detail.getCntrNo());

        //3.cntr_log表
        CntrLog log = new CntrLog();
        BeanUtils.copyProperties(cntrInfo,log);

        cntrInfo.setArea("");
        cntrInfo.setBay("");//清除贝位图
        cntrInfo.setStatus(1);//已出场

        cntrInfo.setMemberId(vo.getMemberId());
        cntrInfo.setUserId(vo.getUserId());
        cntrInfo.setUserName(vo.getUserName());
        if(vo.getIsZzt()==1){//直装
            cntrInfo.setRemark("装车理货(直装)");
            cntrInfo.setCntrWorkRemark(FyEnum.YFCZZ.getName());//已发出(直装)
            cntrInfo.setOperateType("ZCLHZZ");//装车理货(直装)
        }else{
            cntrInfo.setOperateType("ZCLH");//装车理货(出场)
            cntrInfo.setRemark("装车理货(出场)");
            cntrInfo.setCntrWorkRemark(FyEnum.YFC.getName());//已发出
        }
        cntrInfo.setAccesspath(vo.getAccesspath());
        cntrInfo.setUpdatetime(LocalDateTime.now());
        cntrInfo.setTrackOrCar(0);
        cntrInfo.setOutTime(LocalDateTime.now());//出场时间
        cntrInfo.setMachineName(vo.getMachineName());
        log.setStatus(cntrInfo.getStatus());
        log.setMemberId(cntrInfo.getMemberId());
        log.setUserId(cntrInfo.getUserId());
        log.setUserName(cntrInfo.getUserName());
        log.setRemark(cntrInfo.getRemark());
        log.setCntrWorkRemark(cntrInfo.getCntrWorkRemark());
        log.setOperateType(cntrInfo.getOperateType());
        log.setAccesspath(cntrInfo.getAccesspath());
        log.setCreatetime(LocalDateTime.now());
        log.setTrackOrCar(0);
        log.setMachineName(vo.getMachineName());
        TrainPlan plan = planMapper.selectById(detail.getPlanId());
        List<ChargeContract> chargeContracts = chargeContractMapper.selectList(new QueryWrapper<ChargeContract>().eq("disable", 0).le("begin_time", LocalDateTime.now()).ge("end_time", LocalDateTime.now())
                .and(wrapper -> wrapper.eq("contract_name", "标准合同").or().eq("company_id", cntrInfo.getCompanyId())));
        Long contractId=null;

        if (chargeContracts.size() == 1) {
            contractId=chargeContracts.get(0).getId();
        }else if (chargeContracts.size() > 1) {
            contractId=chargeContracts.stream().filter(s -> !"标准合同".equals(s.getContractName())).collect(Collectors.toList()).get(0).getId();
        }
        //生成计费流水
        List<ChargeConfig> configs=chargeConfigService.getListByName("装车");
        if(!configs.isEmpty()){
            List<ChargeItemVo> chargeItemVos = chargeItemService.getChargeItemVoList(configs.stream().map(s -> String.valueOf(s.getChargeItemId())).collect(Collectors.joining(",")));
            List<CntrChargeDetail> cntrChargeDetails=new ArrayList<>();
            CompanyInfo companyInfo = companyInfoMapper.selectById(cntrInfo.getCompanyId());
            //组装一个基础信息
            CntrChargeDetail cntrChargeDetail=new CntrChargeDetail();
            cntrChargeDetail.setYwOrderId(plan.getId().toString());
            cntrChargeDetail.setCntrNo(detail.getCntrNo());
            cntrChargeDetail.setTruckNo(vo.getCarNo());
            cntrChargeDetail.setGoodsName(detail.getGoods());
            cntrChargeDetail.setCntrSize(detail.getCntrSize());
            cntrChargeDetail.setEfFlag(detail.getEfFlag());
            cntrChargeDetail.setCntrNo(detail.getCntrNo());
            cntrChargeDetail.setBillNo(detail.getBillNo());
            cntrChargeDetail.setTallyTime(LocalDateTime.now());
            if (companyInfo!=null){
                cntrChargeDetail.setCompanyId(companyInfo.getId().intValue());
                cntrChargeDetail.setCompanyName(companyInfo.getName());
            }
            cntrChargeDetail.setOrderNo(plan.getTrainPlanNo());
            cntrChargeDetail.setCreateTime(LocalDateTime.now());
            cntrChargeDetails=configService.comCalculateCntrCost(chargeItemVos,cntrChargeDetail,contractId,companyInfo);
            cntrChargeDetailService.saveBatch(cntrChargeDetails);
        }
        logMapper.insert(log);
        infoMapper.updateById(cntrInfo);
        boolean b = updateById(detail);

        //该班列下箱子是否全部理货  手动完工
//        LambdaQueryWrapper<TrainPlanDetail> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(TrainPlanDetail::getDisable,0)
//                .eq(TrainPlanDetail::getPlanId,vo.getPlanId())
//                .eq(TrainPlanDetail::getTallyFlag,0);
//        if (count(wrapper)>0){
//
//        }else{
//            plan.setStatus(10);
//            planMapper.updateById(plan);
//        }
        if (b){
            //寻找有没有同绑定的箱子 赋值车号
            List<TrainPlanDetail> trainPlanDetailList = baseMapper.selectList(new QueryWrapper<TrainPlanDetail>().eq("plan_id", detail.getPlanId())
                    .eq("group_id", detail.getGroupId()).ne("cntr_no", detail.getCntrNo()));
            if(trainPlanDetailList.size()>0){
                for (TrainPlanDetail trainPlanDetail : trainPlanDetailList) {
                    trainPlanDetail.setTrainNumber(vo.getTrainNumber());
                }
                updateBatchById(trainPlanDetailList);
            }

            //分组时间戳 寻找相同 车号的数据 赋值分组id
            List<TrainPlanDetail> trainPlanDetailList1 = baseMapper.selectList(new QueryWrapper<TrainPlanDetail>().eq("plan_id", detail.getPlanId()).eq("disable",0)
                    .eq("train_number", detail.getTrainNumber()).ne("cntr_no", detail.getCntrNo()));
            if(trainPlanDetailList1.size()>0){
                for (TrainPlanDetail trainPlanDetail : trainPlanDetailList1) {
                    trainPlanDetail.setGroupId(detail.getGroupId());
                }
                updateBatchById(trainPlanDetailList1);
            }
            return ResultUtil.ok();
        }
        return ResultUtil.fail();

    }

    @Override
    public ResultUtil<List<TrainPlanDetailVo>> cntrUploadCheck(MultipartFile file) {

        List<TrainPlanDetailVo> list = new ArrayList<>();
        List<String> cntrList = new ArrayList<String>();
        ResultUtil<List<TrainPlanDetailVo>> build = new ResultUtil<>();
        if (file != null) {
            try {
                List<TrainPlanDetailVo> planCntrVos = EasypoiExcelUtils.importExcel(file, 1, 1, TrainPlanDetailVo.class);
                //箱号、运单号、施封号可能存在/,也就是2个箱子
                List<TrainPlanDetailVo> newPlanCntrVos = new ArrayList<>();
                List<CntrSize> cntrSizes = cntrSizeMapper.selectList(Wrappers.<CntrSize>lambdaQuery()
                        .eq(CntrSize::getDisable,0));

                //-------------------------卸车池数据-------------------------
                LambdaQueryWrapper<TrainPlanDetail> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TrainPlanDetail::getDisable,0).eq(TrainPlanDetail::getTallyFlag,0)
                        .eq(TrainPlanDetail::getSignLx,"XC");
                List<TrainPlanDetail> xcData = baseMapper.selectList(wrapper);

                //--------------在场箱-------------------
                LambdaQueryWrapper<CntrInfo> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(CntrInfo::getDisable,0)
                        .eq(CntrInfo::getStatus,0);
                List<CntrInfo> cntrInfoList = infoMapper.selectList(wrapper1);

                List<ProductName> productNames = productNameMapper.selectList(new QueryWrapper<ProductName>().eq("disable", 0));
                for (TrainPlanDetailVo plan : planCntrVos) {
                    String[] cntrNos = plan.getCntrNo().split("/");
                    String[] billNos = new String[]{};
                    if(StrUtil.isNotBlank(plan.getBillNo())){
                        billNos = plan.getBillNo().split("/");
                    }
                    String[] sealNos = new String[]{};
                    //排除施封号0的情况
                    if(StrUtil.isNotBlank(plan.getSealNo())&&(!plan.getSealNo().trim().equals("0"))){
                        sealNos = plan.getSealNo().split("/");
                    }
                    for (int i = 0; i < cntrNos.length; i++) {
                        TrainPlanDetailVo newPlan = new TrainPlanDetailVo();
                        BeanUtils.copyProperties(plan,newPlan);
                        newPlan.setCntrNo(cntrNos[i].trim());
                        //如果没有运单号为空设置null,否则按/拆分分配对应运单号,不够分配说明只有一个按照第一个分配
                        newPlan.setBillNo(billNos.length == 0 ? null:(i < billNos.length ? billNos[i] : billNos[0]));
                        //如果没有施封号为空设置null,否则按/拆分分配对应施封号,不够分配说明只有一个按照第一个分配
                        newPlan.setSealNo(sealNos.length == 0 ? null:(i < sealNos.length ? sealNos[i] : sealNos[0]));
                        // 其他属性根据实际情况设置
                        newPlanCntrVos.add(newPlan);
                    }
                    if(StrUtil.isNotBlank(plan.getWorkCarStr())){
                        if(WorkCarEnum.TRUE.getName().equals(plan.getWorkCarStr())){
                            plan.setWorkCar(WorkCarEnum.TRUE.getValue());
                        }else if(WorkCarEnum.FALSE.getName().equals(plan.getWorkCarStr())){
                            plan.setWorkCar(WorkCarEnum.FALSE.getValue());
                        }
                    }
                }
                List<String> collect =new ArrayList<>();
                if(cntrSizes.size()>0){
                    collect = cntrSizes.stream().map(CntrSize::getCntrName).collect(Collectors.toList());
                }
                List<String> tradeNames =new ArrayList<>();
                if(!productNames.isEmpty()){
                    tradeNames = productNames.stream().map(ProductName::getTradeName).collect(Collectors.toList());
                }
                for (TrainPlanDetailVo c:newPlanCntrVos) { //校验数据
                    if (ObjectUtil.isEmpty(c)|| StrUtil.isBlank(c.getCntrNo())){
                        c.setErrorInfo("文件中有空数据;");
                        list.add(c);
                        break;
                    }
                    c.setCntrNo(StrUtil.isNotBlank(c.getCntrNo()) ? c.getCntrNo().replace(" ", "").trim():"");
                    c.setConsignee(StrUtil.isNotBlank(c.getConsignee())?c.getConsignee().trim():"");//收货人两端去空
                    c.setConsigner(StrUtil.isNotBlank(c.getConsigner())?c.getConsigner().trim():"");//发货人两端去空
                    c.setZhPort(StrUtil.isNotBlank(c.getZhPort())?c.getZhPort().trim():"");//发站两端去空
                    c.setMdPort(StrUtil.isNotBlank(c.getMdPort())?c.getMdPort().trim():"");//到站两端去空
                    c.setCntrSize(c.getCntrSize().split("-")[0]);//箱尺寸   20HC(20英尺9'6"通用箱)
                    String errorInfo = checkCntr(cntrList, c.getCntrNo());
                    if(xcData.size()>0){
                        if(xcData.stream().map(TrainPlanDetail::getCntrNo).collect(Collectors.toList()).contains(c.getCntrNo())){
                            errorInfo += "数据池箱号已存在;";
                        }
                    }
                    if(cntrInfoList.size()>0){
                        if(cntrInfoList.stream().map(CntrInfo::getCntrNo).collect(Collectors.toList()).contains(c.getCntrNo())){
                            errorInfo += "箱子已在场;";
                        }
                    }

                    if (!StrUtil.isNotBlank(c.getCntrSize())) {
                        errorInfo += "箱型未填;";
                    } else {
                        if(c.getCntrSize().indexOf("-")!=-1){
                            c.setCntrSize(c.getCntrSize().split("-")[0]);
                        }
                        if(collect.size()>0){
                            if(!collect.contains(c.getCntrSize())){
                                errorInfo += "箱型不存在;";
                            }
                        }
                    }
                    if (!StrUtil.isNotBlank(c.getEfFlag())){
                        errorInfo += "空重未填;";
                    }else{
                        if("E".equals(c.getEfFlag()) || c.getEfFlag().contains("空")){//空箱
                            c.setEfFlag("E");
                        }else{
                            if (!StrUtil.isNotBlank(c.getGoods())){
                                errorInfo += "品名未填;";
                            }else {
                                if(!tradeNames.contains(c.getGoods())){
                                    errorInfo += "未找到对应品名;";
                                }
                            }
                            c.setEfFlag("F");//重箱
                        }
                    }

                    if (!StrUtil.isNotBlank(c.getMdPort())){
                        c.setMdPort("香炉山");
                    }
                    if (!StrUtil.isNotBlank(c.getZhPort())){
                        errorInfo += "发站未填;";
                    }
                    if (!StrUtil.isNotBlank(c.getConsignee())){
                        errorInfo += "收货人未填;";
                    }
                    c.setErrorInfo(errorInfo);
                    c.setSignLx("XC");
                    list.add(c);
                }
                build = ResultUtil.build(list, ResultUtilCodeEnum.SUCCESS);
            }catch (Exception e){
                e.printStackTrace();
                return ResultUtil.build(400,e.getMessage());
            }
        }
        return build;
    }

    @Override
    public ResultUtil<T> saveTrainPlanDetailList(Integer planId, List<TrainPlanDetail> list) {
        TrainPlan trainPlan = planMapper.selectById(planId);
        List<TrainPlanDetail> trainPlanDetails = baseMapper.selectList(Wrappers.lambdaQuery(TrainPlanDetail.class)
                .eq(TrainPlanDetail::getDisable, 0)
                .eq(TrainPlanDetail::getPlanId, planId));
        trainPlanDetails.forEach(trainPlanDetail -> trainPlanDetail.setDisable(1));
        //旧数据删除
        updateBatchById(trainPlanDetails);
        //保存新数据
        boolean b = saveBatch(list);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public Integer getCountZxcTallyNumber(String ywCode) {
        return baseMapper.selectCountZxcTally(ywCode);
    }

    @Override
    public List<TrainPlanDetail> getXcCntrList(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        LambdaQueryWrapper<TrainPlanDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TrainPlanDetail::getDisable,0)
                        .eq(TrainPlanDetail::getOrderNo,vo.getOrderNo());
        return baseMapper.selectList(wrapper);
    }

    @Override
    public ResultUtil<T> addDetailRet(TrainPlanDetail detail) {
        TrainPlan trainPlan = planMapper.selectOne(new QueryWrapper<TrainPlan>().eq("disable",0).eq("train_plan_no",detail.getOrderNo()));
        if(trainPlan!=null){
            detail.setPlanId(trainPlan.getId());
        }
        boolean b = save(detail);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> updateDetailById(TrainPlanDetail detail) {

        if(!(detail.getOldCntrNo().equals(detail.getCntrNo()))){
            //不能与委托内其他箱号相同
            List<TrainPlanDetail> cntrList = baseMapper.selectList(new QueryWrapper<TrainPlanDetail>().eq("disable", 0).eq("cntr_no", detail.getCntrNo()));
            if (cntrList.size()>0){
                return ResultUtil.build(ResultUtilCodeEnum.CNTR_NO_EXIST);
            }
        }

        boolean b = updateById(detail);

        //修改箱信息 箱动态
        CntrInfo cntrInfo = infoMapper.selectById(detail.getOldCntrNo());

        if(cntrInfo!=null){
            CntrInfo newInfo=new CntrInfo();
            BeanUtils.copyProperties(cntrInfo,newInfo);
            newInfo.setCntrNo(detail.getCntrNo());
            newInfo.setCntrSize(detail.getCntrSize());
            newInfo.setGoods(detail.getGoods());
            newInfo.setMdPort(detail.getMdPort());
            newInfo.setEndPort(detail.getMdPort());
            newInfo.setSealNo(detail.getSealNo());
            if(detail.getWeightPred()!=null){
                newInfo.setWeightPred(detail.getWeightPred());
            }
            if(detail.getShipperWeight()!=null){
                newInfo.setShipperWeight(detail.getShipperWeight());
            }
            if(detail.getCarrierWeight()!=null){
                newInfo.setCarrierWeight(detail.getCarrierWeight());
            }
            newInfo.setZhPort(detail.getZhPort());
            newInfo.setConsignee(detail.getConsignee());
            newInfo.setConsigner(detail.getConsigner());
            newInfo.setBillNo(detail.getBillNo());
            infoService.saveOrUpdate(newInfo);

            if(!(detail.getOldCntrNo().equals(detail.getCntrNo()))){
                //旧的应该设为不在场 或者删掉
                cntrInfo.setStatus(1);
                cntrInfo.setBay("");
                cntrInfo.setArea("");
                infoService.updateById(cntrInfo);
            }
        }

        List<CntrLog> cntrLogs = logService.getBaseMapper().selectList(new QueryWrapper<CntrLog>().eq("disable", 0)
                .eq("cntr_no", detail.getOldCntrNo()).eq("order_no", detail.getOrderNo()));
        if(cntrLogs.size()>0){
            for (CntrLog cntrLog : cntrLogs) {
                cntrLog.setCntrNo(detail.getCntrNo());
                cntrLog.setCntrSize(detail.getCntrSize());
                cntrLog.setGoods(detail.getGoods());
                cntrLog.setMdPort(detail.getMdPort());
                cntrLog.setEndPort(detail.getMdPort());
                cntrLog.setSealNo(detail.getSealNo());
                if(detail.getWeightPred()!=null){
                    cntrLog.setWeightPred(detail.getWeightPred());
                }
                cntrLog.setZhPort(detail.getZhPort());
                cntrLog.setConsignee(detail.getConsignee());
                cntrLog.setConsigner(detail.getConsigner());
                cntrLog.setBillNo(detail.getBillNo());
            }
            logService.updateBatchById(cntrLogs);
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> delBatchDetailRet(TrainPlanVo vo) {
        boolean b=false;
        if(!vo.getDetailList().isEmpty()){
            for (TrainPlanDetail trainPlanDetail : vo.getDetailList()) {
                trainPlanDetail.setDisable(1);
            }
            b = updateBatchById(vo.getDetailList());
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public List<CompanyInfoVo> getXcTrainPlanDetailCompanyList(TrainPlanDetailVo vo) {
        return baseMapper.getXcTrainPlanDetailCompanyList(vo);
    }

    @Override
    public List<TrainPlanDetailVo> getXcDataPoolList(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        IPage<TrainPlanDetailVo> iPage = baseMapper.getXcDataPoolList(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> importXcTrainPlanCntr(HttpServletRequest request,List<TrainPlanDetail> list) {
        UserDto user = TokenUtil.getUser(request);

        list.forEach(item->item.setDisable(0).setCreatetime(LocalDateTime.now()).setUserId(user.getId()).setUserName(user.getRealname()).setAccesspath("PC"));
        LambdaQueryWrapper<CntrInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CntrInfo::getDisable,0);

        List<CntrInfo> infos = infoMapper.selectList(wrapper);
        List<CntrInfo> cntrs = new ArrayList<>();//要批量插入cntr_info的数据
        List<CntrLog> logs = new ArrayList<>();//要批量插入cntr_log的数据
        //班列发运、普通发运、水转铁、提重以及提重回空重箱子的发运到达状态只能有一个
        List<String> ddcntrnoList = new ArrayList<>();
        for (TrainPlanDetail detail : list) {//1234  导入list
            boolean flag = true;
            for (CntrInfo info : infos) {//箱号 3
                if (detail.getCntrNo().equals(info.getCntrNo())){
                    flag = false;
                }
            }
            if (flag){
                //cntr_info表没有箱号则新增
                CntrInfo info = new CntrInfo();
                info.setCntrNo(detail.getCntrNo());
                info.setCntrSize(detail.getCntrSize());
                info.setGoods(detail.getGoods());
                info.setAccesspath("PC");
                info.setRemark("卸车导入");
                info.setCntrWorkRemarkB(DdEnum.DXC.getName());//待卸车
                info.setOperateType("XC");
                info.setTrainNumber(detail.getTrainNumber());
                info.setBillNo(detail.getBillNo());
                info.setSealNo(detail.getSealNo());
                info.setWeightPred(detail.getWeightPred());
                info.setCreatetime(LocalDateTime.now());
                info.setStrands(detail.getStrands());
                info.setSwId(detail.getSwId());
                info.setShipperWeight(detail.getShipperWeight());
                info.setCarrierWeight(detail.getCarrierWeight());
                info.setZhPort(detail.getZhPort());
                info.setConsigner(detail.getConsigner());
                info.setMdPort(detail.getMdPort());
                info.setConsignee(detail.getConsignee());//收货人公司
                CompanyInfo companyInfo = companyInfoMapper.getCompanyIdByName(detail.getConsignee());
                if (companyInfo!=null){
                    info.setCompanyId(companyInfo.getId());//导入set收货人公司id
                }
                info.setWorkCar(detail.getWorkCar());
                info.setConsigneeLx(detail.getConsigneeLxr());
                info.setConsigneePhone(detail.getConsigneeContact());
                info.setStatus(1);
                info.setEfFlag("空".equals(detail.getEfFlag())?"E":"F");
                info.setStartPort(detail.getZhPort());
                info.setEndPort(detail.getMdPort());
                cntrs.add(info);
                CntrLog log = new CntrLog();
                BeanUtils.copyProperties(info,log);
                logs.add(log);
            }else{
                //有箱号则update收货人信息
                CntrInfo info = infoMapper.getCntrInfoById(detail.getCntrNo());
                info.setCntrSize(detail.getCntrSize());
                info.setGoods(detail.getGoods());
                info.setAccesspath("PC");
                info.setRemark("卸车导入");
                info.setCntrWorkRemarkB(DdEnum.DXC.getName());//待卸车
                info.setCntrWorkRemark(null);
                ddcntrnoList.add(info.getCntrNo());
                info.setOperateType("XC");
                info.setTrainNumber(detail.getTrainNumber());
                info.setBillNo(detail.getBillNo());
                info.setSealNo(detail.getSealNo());
                info.setWeightPred(detail.getWeightPred());
                info.setCreatetime(LocalDateTime.now());
                info.setStrands(detail.getStrands());
                info.setSwId(detail.getSwId());
                info.setShipperWeight(detail.getShipperWeight());
                info.setCarrierWeight(detail.getCarrierWeight());
                info.setZhPort(detail.getZhPort());
                info.setConsigner(detail.getConsigner());
                info.setMdPort(detail.getMdPort());
                info.setConsignee(detail.getConsignee());//收货人公司
                CompanyInfo companyInfo = companyInfoMapper.getCompanyIdByName(detail.getConsignee());
                if (companyInfo!=null){
                    info.setCompanyId(companyInfo.getId());//导入set收货人公司id
                }
                info.setWorkCar(detail.getWorkCar());
                info.setConsigneeLx(detail.getConsigneeLxr());
                info.setConsigneePhone(detail.getConsigneeContact());
                info.setStartPort(detail.getZhPort());
                info.setEndPort(detail.getMdPort());
                info.setStatus(1);
                info.setEfFlag("空".equals(detail.getEfFlag())?"E":"F");
                cntrs.add(info);
                CntrLog log = new CntrLog();
                BeanUtils.copyProperties(info,log);
                logs.add(log);
            }
        }
        infoService.saveOrUpdateBatch(cntrs);
        if(!ddcntrnoList.isEmpty()){
            infoService.update(null,Wrappers.<CntrInfo>lambdaUpdate()
                    .set(CntrInfo::getCntrWorkRemark,null)
                    .in(CntrInfo::getCntrNo,ddcntrnoList));
        }
        logService.saveBatch(logs);
        boolean b = saveBatch(list);
        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> deleteDetail(HttpServletRequest request, CntrLogVo vo) {
        TrainPlanDetail detail = baseMapper.getDetailById(vo.getId());

        //修改cntrinfo表 发运状态   "待发运"
        CntrInfo info = infoMapper.selectCntrByCntrNo(detail.getCntrNo());
        info.setCntrWorkRemark(FyEnum.DFY.getName());//待发运
        infoMapper.updateById(info);

        //修改log表 备注  "待发运"
//        CntrLog log = new CntrLog();
        CntrLog log = logMapper.selectMsgByCntr(detail);
        log.setCntrWorkRemark(FyEnum.DFY.getName());//待发运
        logMapper.updateById(log);
        //清单表
        detail.setDisable(1);
        boolean b = updateById(detail);
        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> deleteXcCntr(Long id) {
        TrainPlanDetail detail = getById(id);
        detail.setDisable(1);
        //清单
        if (updateById(detail)){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> updatePoolCntrMsg(TrainPlanDetail detail) {
        if (updateById(detail)){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public List<TrainPlanDetailVo> getZzTrainPlanDetail(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        IPage<TrainPlanDetailVo> iPage = baseMapper.getZzTrainPlanDetail(page,vo);
        return iPage.getRecords();
    }

    @Override
    public List<TrainPlanDetailVo> getZtTrainPlanDetail(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        IPage<TrainPlanDetailVo> iPage = baseMapper.getZtTrainPlanDetail(page,vo);
        return iPage.getRecords();
    }

    @Override
    public List<TrainPlanDetailVo> getXcTrainPlanDetail(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        //车辆预约内的cntr(提空，提重)  //不过滤 显示所有
//        List<String> cntrs = reservationMapper.selectYyCntrList();
//        vo.setYycntrList(cntrs);
        IPage<TrainPlanDetailVo> iPage = baseMapper.getXcTrainPlanDetail(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> carTallyDzg(TrainPlanDetailVo vo) {

        if (vo.getBay()!=null && vo.getBay()!=""){
            //贝位校验
            if (!(vo.getBay().matches(".*[\u4e00-\u9fa5]+.*")) && upCntrCheck(vo.getBay())){
                return ResultUtil.build(400, "贝位"+vo.getBay()+"上面存在箱子,请检查");
            }
        }

        CntrInfo one = infoMapper.selectOne(Wrappers.<CntrInfo>lambdaQuery()
                .eq(CntrInfo::getCntrNo, vo.getCntrNo()));

        if (one == null) {
            return ResultUtil.build(400, "集装箱不存在");
        }

        if (one.getStatus() != 0) {
            return ResultUtil.build(400, "该箱子不在场");
        }
        //1.修改detail表 理货状态
        TrainPlanDetail detail = getById(vo.getId());
        detail.setDisable(1);//计划清单表删除
        boolean b = updateById(detail);

        //cntr_info清除贝位，带整改区
        CntrInfo info = infoMapper.getCntrInfoById(vo.getCntrNo());
        info.setBay("");//清空贝位
        info.setStatus(0);//在场
        info.setArea("待整改区");//区域
        info.setLockFlag(1);
        info.setLockRemark("待整改");
        info.setLockStart(LocalDateTime.now());
        info.setUserName(vo.getUserName());
        info.setCntrWorkRemark(FyEnum.DZG.getName());
        info.setOperateType("ZCLHDZG");//装车理货(出场)
        info.setRemark("装车理货(待整改)");
        info.setMachineName(vo.getMachineName());
        infoMapper.updateById(info);
        //log表日志
        CntrLog log = new CntrLog();
        BeanUtils.copyProperties(info,log);
        log.setCreatetime(LocalDateTime.now());
        logService.save(log);
//        logMapper.insert(log);
        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> saveDetailMsgOne(TrainPlanDetail detail) {
        SysUser user = userMapper.selectById(detail.getUserId());
        //先删除Detail表中的箱子信息
//        LambdaUpdateWrapper<TrainPlanDetail> wrapper = new LambdaUpdateWrapper<>();
//        wrapper.eq(TrainPlanDetail::getPlanId,detail.getPlanId())
//                .eq(TrainPlanDetail::getTallyFlag,0)//未理货的箱子
//                .set(TrainPlanDetail::getDisable,1);
//        boolean b = update(wrapper);

        //再新增(
        int insert = 0;
        List<String> cntrNoList = detail.getCntrNoList();
        if (cntrNoList==null || cntrNoList.size()==0){
            return ResultUtil.ok();//没有选择任何箱子
        }

        for (String cntrNo : cntrNoList) {

            //校验是否已经绑定数据
            LambdaUpdateWrapper<TrainPlanDetail> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(TrainPlanDetail::getPlanId,detail.getPlanId()).eq(TrainPlanDetail::getDisable,0)
                    .eq(TrainPlanDetail::getCntrNo,cntrNo);
            int num = count(wrapper);
            if(num>0){
                return ResultUtil.build(400,"该箱子已经录入了！");
            }

            //cntrinfo 发运箱动态信息
            CntrInfo cntrInfo = infoMapper.selectById(cntrNo);
            cntrInfo.setCntrWorkRemark(FyEnum.YPF.getName());
            cntrInfo.setCntrWorkRemarkB(null);
            infoMapper.updateById(cntrInfo);
            //cntrlog 发运箱动态信息
            CntrLog log = new CntrLog();
            BeanUtils.copyProperties(cntrInfo,log);
            log.setCreatetime(LocalDateTime.now());
            log.setAccesspath("PC");
            logMapper.insert(log);
            //从yw_order_cntr中获取专用线
            String zyx = cntrMapper.getZyxByCntrNoAndOrderNo(cntrNo, detail.getOrderNo());
            BeanUtils.copyProperties(cntrInfo,detail);
            //班列下集装箱详情的车牌号是装车理货的车皮号,不是箱子带来的车牌号
            detail.setCarNo(null);
            detail.setCreatetime(LocalDateTime.now());
            detail.setUserName(user.getRealname());
            detail.setArea(cntrInfo.getArea());
            detail.setBay(cntrInfo.getBay());
            detail.setAccesspath("PC");
            detail.setLhWeight(cntrInfo.getLhWeight());//理货重量
            if(cntrInfo.getCompanyId()!=null){
                detail.setCompanyId(cntrInfo.getCompanyId().intValue());//货主/客户id
            }
            //分组时间戳
            long millis = System.currentTimeMillis();
            detail.setGroupId(String.valueOf(millis));//分组时间戳id
            detail.setLineOrYard(zyx);//专用线
            insert = baseMapper.insert(detail);
        }
        if (insert==0){
            return ResultUtil.fail();
        }
        return ResultUtil.ok();
    }

    @Override
    public ResultUtil<T> addXcData(TrainPlanDetailVo vo1) {
        boolean b = CheckUtils.checkCntrNo(vo1.getCntrNo());
        if (!b){
            return ResultUtil.build(400,"箱号错误(4位大写字母+7位数字)");
        }
        CntrTallyVo vo = new CntrTallyVo();
        if(vo1.getIsZzt()==1) {

            //pad选择的车牌号所属的卡口表id
            DeclareCar declareCar = declareCarMapper.selectById(vo1.getDeclareId());

            YwOrderCntr orderCntr = cntrMapper.getorderNoByCntrNo(vo1.getCntrNo());
            if(orderCntr == null){
                return ResultUtil.build(400, "该集装箱没有提箱委托");
            }
            //显示提箱委托
            VehicleReservationVo reservationVo = new VehicleReservationVo();
            reservationVo.setCarNo(declareCar.getCarNo());
            List<YwOrder> txOrder = orderMapper.getTxOrder(reservationVo);
            if (txOrder.size() > 0) {
                if (!(txOrder.stream().map(YwOrder::getOrderNo).collect(Collectors.toList()).contains(orderCntr.getOrderNo()))) {
                    return ResultUtil.build(400, "该车辆没有授权提箱操作！");
                }
            } else {
                return ResultUtil.build(400, "该车辆没有授权提箱操作！");
            }

            //提箱 已受理的箱子集合
            List<YwOrderCntr> list = cntrMapper.getTxYslCntrList();
            long num = list.stream().filter(s -> s.getCntrNo().equals(vo1.getCntrNo())).count();
            //手动录入的箱子必须是已受理的
            if (num == 0) {
                return ResultUtil.build(400, "该集装箱没有提箱委托");
            }
            vo.setYwOrderNo(orderCntr.getOrderNo());
            vo.setDeclareId(vo1.getDeclareId());//车牌所属卡口表id
            vo.setCarNo(declareCar.getCarNo());//
            vo1.setConsigner(orderCntr.getShipper());
            vo1.setConsignee(orderCntr.getConsignee());
            vo1.setZhPort(orderCntr.getInitialStation());
            vo1.setMdPort(orderCntr.getDestination());
        }
        //add 卸车数据池Msg
        TrainPlanDetail detail = new TrainPlanDetail();
        BeanUtils.copyProperties(vo1,detail);
        detail.setBay("");
        detail.setSignLx("XC");
        save(detail);

        vo.setId(detail.getId());
        vo.setCntrNo(vo1.getCntrNo());
        vo.setArea(vo1.getArea());
        vo.setBay(vo1.getBay());
        vo.setTrainPlanNo(vo1.getTrainPlanNo());
        vo.setOrderNo(vo1.getOrderNo());
        vo.setArea(vo1.getArea());
        vo.setBay(vo1.getBay());
        vo.setCntrSize(vo1.getCntrSize());
        vo.setEfFlag(vo1.getEfFlag());
        vo.setGoods(vo1.getGoods());
        vo.setMachineName(vo1.getMachineName());
        vo.setTrainPlanNo(vo1.getTrainPlanNo());
        //理货操作
        if(vo1.getIsZzt()==1){
            return infoService.cntrXcTallyZt(vo);
        }
        return infoService.cntrXcTally(vo);

    }

    @Override
    public ResultUtil<T> updateConsigneeMsg(TrainPlanDetailVo vo) {
        List<String> list = vo.getCntrNoList();//Detail表id 集合
        List<CntrInfo> cntrInfoList = new ArrayList<>();
        List<TrainPlanDetail> detailList = new ArrayList<>();
        for (String id : list) {
            TrainPlanDetail detail = getById(id);
            detail.setConsignee("".equals(vo.getConsignee())?detail.getConsignee():vo.getConsignee());//收货人
            detail.setConsigneeLxr("".equals(vo.getConsigneeLxr())?detail.getConsigneeLxr():vo.getConsigneeLxr());//收货联系人
            detail.setConsigneeContact("".equals(vo.getConsigneeContact())?detail.getConsigneeContact():vo.getConsigneeContact());//收货联系人方式
            detail.setMdPort("".equals(vo.getMdPort())?detail.getMdPort():vo.getMdPort());//到站信息
            detailList.add(detail);

            CntrInfo info = infoMapper.getCntrInfoById(detail.getCntrNo());
            info.setConsignee("".equals(vo.getConsignee())?info.getConsignee():vo.getConsignee());//收货人
            info.setConsigneeLx("".equals(vo.getConsigneeLxr())?info.getConsigneeLx():vo.getConsigneeLxr());//收货联系人
            info.setConsigneePhone("".equals(vo.getConsigneeContact())?info.getConsigneePhone():vo.getConsigneeContact());//收货联系人方式
            info.setEndPort("".equals(vo.getMdPort())?info.getEndPort():vo.getMdPort());//到站信息
            cntrInfoList.add(info);
        }
        infoService.updateBatchById(cntrInfoList);//箱信息表
        boolean b = updateBatchById(detailList);//班列清单表
        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    private String checkCntr(List<String> cntrList, String cntrNo) throws Exception {
//        boolean checkDigit = CheckUtils.checkDigit(cntrNo);
//        if (!checkDigit) {
//            return "箱号格式不正确;";
//        }
        if(!Pattern.compile("[A-Z]*").matcher(cntrNo.substring(0,4)).matches()){
            return "箱号前4位必须是大写字母;";
        }
        //箱号校验暂时仅校验位数
        if (cntrNo.trim().length() != 11) {
            return "箱号格式不正确;";
        }
        if (cntrList.contains(cntrNo)) {
            return "箱号重复;";
        }
        cntrList.add(cntrNo);
        return "";
    }

    //只赋给目标类为null 的字段
    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue != null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }


    public boolean upCntrCheck(String cntrNo) {

        String[] bays = cntrNo.split("-");
        String area = bays[0];
        String bay1 = bays[1];
        String bay2 = bays[2];
        String bay3 = bays[3];
        //贝位小于10加0
        int i = Integer.parseInt(bay1);
        String b = i > 9 ? bay1:"0"+ i;
        //上面一层
        StringBuilder up = new StringBuilder();

        up.append(area).append("-").append(b).append("-").append(bay2).append("-").append(Integer.parseInt(bay3) + 1);

        if (up.length() > 0){
            //上面箱
            CntrInfo one = infoMapper.selectOne(Wrappers.<CntrInfo>lambdaQuery().eq(CntrInfo::getBay, up.toString()).ne(CntrInfo::getCntrNo,cntrNo)
                    .eq(CntrInfo::getDisable, 0).eq(CntrInfo::getStatus,0).select(CntrInfo::getCntrNo,CntrInfo::getCntrSize,CntrInfo::getBay,CntrInfo::getEfFlag));

            if (one != null) {
                return true;
            }
        }
        return false;
    }

    private final static String TRAINPLANDETAIL_REPORT_EXCEL_PATH = "static/download/装车计划班列箱信息导出.xlsx";

    @Override
    public void exportTrainPlanDetailReport(TrainPlanDetailVo vo, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new ConcurrentHashMap<>();
        TrainPlan trainPlan = planMapper.selectById(vo.getPlanId());
        List<TrainPlanDetailVo> list = baseMapper.getTrainPlanDetailList(vo);

        for (TrainPlanDetailVo detailVo: list){
            if(detailVo.getIsZzt().equals(0)){
                detailVo.setIsZztText("否");
            }else if(detailVo.getIsZzt().equals(1)){
                detailVo.setIsZztText("是");
            }
            if(detailVo.getEfFlag().equals("F")){
                detailVo.setEfFlag("重");
            }else if(detailVo.getEfFlag().equals("E")){
                detailVo.setEfFlag("空");
            }
            if(detailVo.getTallyFlag().equals(0)){
                detailVo.setTallyFlagText("未理货");
            }else if(detailVo.getTallyFlag().equals(1)){
                detailVo.setTallyFlagText("已理货");
            }
            Integer shipVia = cntrMapper.getShipViaByCntrNo(detailVo.getCntrNo(), detailVo.getOrderNo());
            if(shipVia==0 && !detailVo.getOrderNo().startsWith("SGJ")){
                detailVo.setShipViaName("普通发运");
            }else if(shipVia==1 && !detailVo.getOrderNo().startsWith("SGJ")){
                detailVo.setShipViaName("班列发运");
            }else if(detailVo.getOrderNo().startsWith("SGJ")){
                detailVo.setShipViaName("散改集");
            }else if (shipVia==2){
                detailVo.setShipViaName("水转铁");
            }
            //合并需要车号比对,设置空字符串好处理
            if(StrUtil.isBlank(detailVo.getCarNo())){
                detailVo.setCarNo("");
            }
        }
        map.put("trainPlanNo",trainPlan.getTrainPlanNo());
        map.put("list",list);
        TemplateExportParams params = new TemplateExportParams(TRAINPLANDETAIL_REPORT_EXCEL_PATH);
        Workbook book = ExcelExportUtil.exportExcel(params, map);
        //合并
        int startRow = 3;
        int size = 0;
        int merge = 0;
        String mergeCom = "";
        String mergeCom2 = "";
        Map<Integer, int[]> map2 = new HashMap<>();
        //车号和分组都一致情况下合并车号
        map2.put(1, null);
        for (int i = 0; i < list.size(); i++) {
            if ((list.get(i).getGroupId().equals(mergeCom)&&list.get(i).getTrainNumber().equals(mergeCom2)) && (i != (list.size() - 1))) {
                //合并
                merge += 1;
            } else if (i == (list.size() - 1)) {
                //最后一条
                if (merge > 0) {
                    int lastMerge = list.get(i).getGroupId().equals(mergeCom)&&list.get(i).getTrainNumber().equals(mergeCom2)?0:1;
                    book.getSheetAt(0).addMergedRegion(new CellRangeAddress(startRow+size - merge, startRow+size + 1-lastMerge, 1, 1));
                }else{
                    int lastMerge = list.get(i).getGroupId().equals(mergeCom)&&list.get(i).getTrainNumber().equals(mergeCom2)?0:1;
                    book.getSheetAt(0).addMergedRegion(new CellRangeAddress(startRow+size , startRow+size + 1-lastMerge, 1, 1));
                }
            } else {
                //判断前面是否有合并
                if (merge > 0) {
                    book.getSheetAt(0).addMergedRegion(new CellRangeAddress(startRow+size - merge, startRow+size, 1, 1));
                }
                merge = 0;
                mergeCom = list.get(i).getGroupId();
                mergeCom2 = list.get(i).getTrainNumber();
            }
            size += 1;
        }
        FileExcelUtil.downloadExcelIo(book, request, response, "装车计划班列箱信息导出");
    }

    @Override
    public List<TrainPlanDetailVo> getTrainPlanDetail(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        IPage<TrainPlanDetailVo> iPage = baseMapper.getTrainPlanDetail1(page,vo);
        return iPage.getRecords();
    }

    @Override
    public List<TrainPlanDetailVo> getTrainPlanDetail(TrainPlanDetailVo vo) {
        return baseMapper.getExportDetail(vo);
    }

    @Override
    public ResultUtil<T> deleteCntrOrderMsg(TrainPlanDetailVo vo) {
        List<String> list = vo.getCntrNoList();//Detail表id 集合
        boolean b = infoService.removeByIds(list);//箱信息表

        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> zcUpdateCarNo(TrainPlanDetailVo vo) {
        TrainPlanDetail trainPlanDetail = baseMapper.selectById(vo.getId());
        trainPlanDetail.setTrainNumber(vo.getTrainNumber());
        trainPlanDetail.setSealNo(vo.getSealNo());

        if(StringUtils.isNotEmpty(trainPlanDetail.getGroupId())){
            List<TrainPlanDetail> trainPlanDetails = baseMapper.selectList(new QueryWrapper<TrainPlanDetail>().eq("disable", 0).eq("group_id", trainPlanDetail.getGroupId()));
            if(trainPlanDetails.size()>0){
                for (TrainPlanDetail planDetail : trainPlanDetails) {
                    planDetail.setTrainNumber(vo.getTrainNumber());
                }
                updateBatchById(trainPlanDetails);
            }
        }


        CntrInfo cntrInfo = infoMapper.selectById(trainPlanDetail.getCntrNo());
        cntrInfo.setTrainNumber(vo.getTrainNumber());
        cntrInfo.setSealNo(vo.getSealNo());
        cntrInfo.setMachineName(vo.getMachineName());
        List<YwOrderCntr> cntrList = cntrMapper.selectList(new QueryWrapper<YwOrderCntr>().eq("disable", 0)
                .eq("order_no", trainPlanDetail.getOrderNo()).eq("cntr_no", trainPlanDetail.getCntrNo()));
        if(cntrList.size()>0){
            YwOrderCntr ywOrderCntr = cntrList.get(0);
            ywOrderCntr.setTruckNo(vo.getTrainNumber());
            ywOrderCntr.setSealNo(vo.getSealNo());
            cntrMapper.updateById(ywOrderCntr);
        }
        int i = baseMapper.updateById(trainPlanDetail);
        infoMapper.updateById(cntrInfo);
        if(i>0){
            return ResultUtil.ok();
        }else{
            return ResultUtil.fail();
        }
    }

    @Override
    public List<TrainPlanDetailVo> getZcAndXcDetail(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        IPage<TrainPlanDetailVo> iPage = baseMapper.getZcAndXcDetail(page,vo);
        return iPage.getRecords();
    }

    @Override
    public List<TrainPlanDetailVo> getDdCntrPush(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        IPage<TrainPlanDetailVo> iPage = baseMapper.getDdCntrPush(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> updateConsignee(DdPushCntrVo vo) {

        //卸车清单表--收货人
        List<TrainPlanDetailVo> detailList = vo.getCntrList();
        List<TrainPlanDetail> rel = new ArrayList<>();//卸车清单
        List<CntrInfo> rel1 = new ArrayList<>();//箱信息
        List<CntrLog> rel2 = new ArrayList<>();//箱动态

        for (TrainPlanDetailVo detail : detailList) {
            //卸车清单表--收货人
            TrainPlanDetail one = getById(detail.getId());
            one.setConsignee(vo.getCompanyName());
            one.setTsNum(vo.getTsNum());//组别号
            rel.add(one);
            //箱信息--收货人
            CntrInfo info = infoMapper.getCntrInfoById(detail.getCntrNo());
            info.setConsignee(vo.getCompanyName());
            info.setPayer(vo.getCompanyName());
            rel1.add(info);
            //箱动态
            TrainPlan plan = planMapper.selectById(detail.getPlanId());
            CntrLog log = logMapper.getByCntrNoAndOrderNo(detail.getCntrNo(),plan.getTrainPlanNo());
            log.setConsignee(vo.getCompanyName());
            rel2.add(log);

        }
        boolean b = saveOrUpdateBatch(rel);
        infoService.updateBatchById(rel1);
        logService.updateBatchById(rel2);

        //消息提醒
        List<UserMember> users = memberMapper.getAllByComName(vo.getCompanyName());
        notifyService.sendMsgToCom(vo.getCntrList().get(0).getZhPort(),users,vo.getUserId(),vo.getTsNum());
        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public List<TrainPlanDetailVo> getDdCntrDetail(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        IPage<TrainPlanDetailVo> iPage = baseMapper.getDdCntrDetail(page,vo);
        return iPage.getRecords();
    }


    private final static String ZC_EXPORT_EXCEL_PATH = "static/download/集装箱装车清单导出.xlsx";
    private final static String XC_EXPORT_EXCEL_PATH = "static/download/集装箱卸车清单导出.xlsx";

    @Override
    public void exportZxDetail(HttpServletRequest request, HttpServletResponse response, TrainPlanDetailVo vo) {
        Page<TrainPlanDetailVo> page = new Page<>(vo.getPageIndex(), vo.getPageSize());
        IPage<TrainPlanDetailVo> iPage = baseMapper.getZcAndXcDetail(page,vo);
        Map<String, Object> map = new HashMap<>();
        map.put("list", iPage.getRecords());
        if("ZC".equals(vo.getType())){
            TemplateExportParams params = new TemplateExportParams(ZC_EXPORT_EXCEL_PATH);
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
            FileExcelUtil.downloadExcelIo(workbook, request, response, "集装箱装车清单导出");
        }else{
            TemplateExportParams params = new TemplateExportParams(XC_EXPORT_EXCEL_PATH);
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
            FileExcelUtil.downloadExcelIo(workbook, request, response, "集装箱卸车清单导出");
        }
    }

    @Override
    public ResultUtil<T> updateCntrWg(TrainPlanDetailVo vo) {
        List<TrainPlanDetail> rel = new ArrayList<>();

        long time = System.currentTimeMillis();//车次(时间戳)
        LocalDateTime now = LocalDateTime.now();
        List<TrainPlanDetail> detailList = vo.getCntrList();
        for (TrainPlanDetail detail : detailList) {
            detail.setWgTrip(String.valueOf(time));
            detail.setWgTime(now);
            rel.add(detail);
        }
        boolean b = saveOrUpdateBatch(rel);
        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> retractRet(TrainPlanDetailVo vo) {

        TrainPlanDetail detail = getById(vo.getId());
        //detail表
//        detail.setDisable(1);//删除清单表
        detail.setTallyFlag(0);
        detail.setTrainNumber(null);
        detail.setZxTime(null);
        detail.setTallyUserId(null);
        detail.setTallyMemberId(null);
        detail.setTallyUserName(null);
        int i = baseMapper.updateById(detail);
        //yw_order_cntr表
        if (vo.getOrderNo()!= null && !"".equals(vo.getOrderNo())){
            YwOrderVo order = orderMapper.getYwOrderByOrderNo(vo.getOrderNo());
            if (order != null){
                LambdaQueryWrapper<YwOrderCntr> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(YwOrderCntr::getOrderNo,order.getOrderNo())
                        .eq(YwOrderCntr::getCntrNo,vo.getCntrNo())
                        .eq(YwOrderCntr::getDisable,0)
                        .eq(YwOrderCntr::getTallyState,10);
                YwOrderCntr one = cntrMapper.selectOne(wrapper);
                one.setTruckNo(null);//清空车皮号
                one.setZcTallyFlag(null);//清空车皮号
                one.setZcTime(null);
                one.setZcUser(null);
                cntrMapper.updateById(one);
            }
        }
        //cntr_info表
        CntrInfo cntrInfo = infoMapper.getCntrInfoById(detail.getCntrNo());
//            cntrInfo
        cntrInfo.setArea(vo.getArea());//前端传区域
        cntrInfo.setBay(vo.getBay());//前端传贝位
        cntrInfo.setStatus(0);//在场
        cntrInfo.setRemark("撤回");
        cntrInfo.setCntrWorkRemark(FyEnum.YPF.getName());//还原理货之前状态 已配发
        cntrInfo.setCntrWorkRemarkB(null);//还原理货之前状态 已配发
        cntrInfo.setMachineName(vo.getMachineName());
        infoMapper.updateById(cntrInfo);

        //cntr_log表
        CntrLog log = new CntrLog();
        BeanUtils.copyProperties(cntrInfo,log);
        log.setCreatetime(LocalDateTime.now());
        logMapper.insert(log);
        if (i>0){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public List<TrainPlanDetailVo> getZtTrainPlanDetailOne(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        List<String> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(vo.getOrderNos())){
            if(vo.getOrderNos().indexOf(",")!=-1){
                String[] split = vo.getOrderNos().split(",");
                for (String s : split) {
                    list.add(s);
                }
            }else{
                list.add(vo.getOrderNos());
            }
        }
        vo.setOrderNoList(list);
        IPage<TrainPlanDetailVo> iPage = baseMapper.getZtTrainPlanDetailOne(page,vo);
        return iPage.getRecords();
    }

    @Override
    public List<TrainPlanDetailVo> getPadList1(Page<TrainPlanDetailVo> page, TrainPlanDetailVo vo) {
        List<String> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(vo.getOrderNos())){
            if(vo.getOrderNos().indexOf(",")!=-1){
                String[] split = vo.getOrderNos().split(",");
                for (String s : split) {
                    list.add(s);
                }
            }else{
                list.add(vo.getOrderNos());
            }
        }
        vo.setOrderNoList(list);
        IPage<TrainPlanDetailVo> iPage = baseMapper.getPadList1(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<List<TrainPlanDetailVo>> zcCntrUploadCheck(MultipartFile file) {
        CntrInfoVo vo=new CntrInfoVo();
        List<CntrInfoVo> cntrInfoAll = infoService.getCntrInfoAll(vo);

        List<TrainPlanZcdetail> trainPlanZcdetails = trainPlanZcdetailMapper.selectList(new QueryWrapper<TrainPlanZcdetail>().eq("disable", 0)
                .eq("confirm_flag", 0));

        List<TrainPlanDetailVo> list = new ArrayList<>();
        ResultUtil<List<TrainPlanDetailVo>> build = new ResultUtil<>();
        if (file != null) {
            try {
                List<TrainPlanDetailVo> planCntrVos = EasypoiExcelUtils.importExcel(file, 0, 1, TrainPlanDetailVo.class);
                List<TrainPlanDetailVo> newPlanCntrVos  = planCntrVos.stream().filter(s -> StringUtils.isNotEmpty(s.getGroupId())).sorted(Comparator.comparing(TrainPlanDetailVo::getGroupId)).collect(Collectors.toList());
                for (TrainPlanDetailVo planCntrVo : planCntrVos) {
                    if(StringUtils.isEmpty(planCntrVo.getGroupId())){
                        newPlanCntrVos.add(planCntrVo);
                    }
                }

                for (TrainPlanDetailVo c:newPlanCntrVos) { //校验数据
                    if (ObjectUtil.isEmpty(c)|| StrUtil.isBlank(c.getCntrNo())){
                        c.setErrorInfo("文件中有空数据;");
                        list.add(c);
                        break;
                    }
                    TrainPlanDetailVo trainPlanDetailVo = checkImportCntr(cntrInfoAll, c,list,trainPlanZcdetails);
                    list.add(trainPlanDetailVo);
                }
                build = ResultUtil.build(list, ResultUtilCodeEnum.SUCCESS);
            }catch (Exception e){
                e.printStackTrace();
                return ResultUtil.build(400,e.getMessage());
            }
        }
        return build;



    }

    private TrainPlanDetailVo checkImportCntr(List<CntrInfoVo> cntrList, TrainPlanDetailVo trainPlanDetailVo,List<TrainPlanDetailVo> list,List<TrainPlanZcdetail> trainPlanZcdetails) {
        trainPlanDetailVo.setErrorInfo("");

        if(trainPlanZcdetails.size()>0){
            List<TrainPlanZcdetail> collect = trainPlanZcdetails.stream().filter(s -> s.getCntrNo().equals(trainPlanDetailVo.getCntrNo())).collect(Collectors.toList());
            if(!(collect.size()>0)){
                trainPlanDetailVo.setErrorInfo(trainPlanDetailVo.getErrorInfo()+"该箱号没有导入装车清单,请检查;");
            }
        }

        if(!Pattern.compile("[A-Z]*").matcher(trainPlanDetailVo.getCntrNo().substring(0,4)).matches()){
            trainPlanDetailVo.setErrorInfo(trainPlanDetailVo.getErrorInfo()+"箱号前4位必须是大写字母;");
        }
        //箱号校验暂时仅校验位数
        if (trainPlanDetailVo.getCntrNo().trim().length() != 11) {
            trainPlanDetailVo.setErrorInfo(trainPlanDetailVo.getErrorInfo()+"箱号格式不正确;");
        }
        if (cntrList.contains(trainPlanDetailVo.getCntrNo())) {
            trainPlanDetailVo.setErrorInfo(trainPlanDetailVo.getErrorInfo()+"箱号重复;");
        }
        if(cntrList.size()>0){
            List<CntrInfoVo> collect = cntrList.stream().filter(s -> s.getCntrNo().equals(trainPlanDetailVo.getCntrNo())).collect(Collectors.toList());
            if(collect.size()>0){
                CntrInfoVo cntrInfoVo = collect.get(0);
                BeanUtils.copyProperties(cntrInfoVo,trainPlanDetailVo);
                trainPlanDetailVo.setErrorInfo("");
                //校验分组
                List<TrainPlanDetailVo> trainPlanDetailVos = list.stream().filter(s -> StringUtils.isNotEmpty(s.getGroupId()) && s.getGroupId().equals(trainPlanDetailVo.getGroupId())).collect(Collectors.toList());
                if(trainPlanDetailVos.size()>0){
                    if(trainPlanDetailVos.size()>1){
                        trainPlanDetailVo.setErrorInfo(trainPlanDetailVo.getErrorInfo()+"无法编组3个以上的箱子;");
                    }else{
                        if (trainPlanDetailVos.get(0).getCntrSize().startsWith("40") && cntrInfoVo.getCntrSize().startsWith("40")) {
                            trainPlanDetailVo.setErrorInfo(trainPlanDetailVo.getErrorInfo()+"两个箱子只能是一个 40 尺和一个 20 尺，或两个 20 尺;");
                        }
                    }
                }

                if("1".equals(cntrInfoVo.getNoSelect()) || "3".equals(cntrInfoVo.getNoSelect()) || "4".equals(cntrInfoVo.getNoSelect())){
                    trainPlanDetailVo.setErrorInfo(trainPlanDetailVo.getErrorInfo()+"该箱号无法导入;");
                }
                if(StringUtils.isEmpty(cntrInfoVo.getConsigneeLx()) || StringUtils.isEmpty(cntrInfoVo.getConsigneeContact())){
                    trainPlanDetailVo.setErrorInfo(trainPlanDetailVo.getErrorInfo()+"箱子收货联系人及联系方式为空,无法发运;");
                }
            }else{
                trainPlanDetailVo.setErrorInfo(trainPlanDetailVo.getErrorInfo()+"该箱号不存在,无法导入;");
            }
        }


        return trainPlanDetailVo;
    }

    @Override
    public ResultUtil<T> importZcCntr(HttpServletRequest request,TrainPlanVo vo) {
        boolean b=false;
        UserDto user = TokenUtil.getUser(request);
//        TrainPlan trainPlan = planMapper.selectById(vo.getId());
        List<TrainPlanDetail> detailList = vo.getDetailList();
        //校验是否已经绑定数据
        LambdaUpdateWrapper<TrainPlanDetail> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(TrainPlanDetail::getPlanId,vo.getId()).eq(TrainPlanDetail::getDisable,0)
                .in(TrainPlanDetail::getCntrNo,detailList.stream().map(TrainPlanDetail::getCntrNo).collect(Collectors.toList()));
        int num = count(wrapper);
        if(num>0){
            return ResultUtil.build(400,"该箱子已经绑定过了！");
        }


        Map<String, List<TrainPlanDetail>> collect = detailList.stream().collect(Collectors.groupingBy(TrainPlanDetail::getGroupId));
        Iterator<Map.Entry<String, List<TrainPlanDetail>>> iterator = collect.entrySet().iterator();

        List<CntrInfo> cntrInfos=new ArrayList<>();
        List<CntrLog> cntrLogs=new ArrayList<>();
        List<TrainPlanDetail> trainPlanDetails=new ArrayList<>();
        while (iterator.hasNext()) {
            Map.Entry<String, List<TrainPlanDetail>> entry = iterator.next();
            List<TrainPlanDetail> list=entry.getValue();
            //分组时间戳
            long millis = System.currentTimeMillis();
            if(list.size()>1){
                for (TrainPlanDetail detail : list) {
                    //cntrinfo 发运箱动态信息
                    CntrInfo cntrInfo = infoMapper.selectById(detail.getCntrNo());
                    cntrInfo.setCntrWorkRemark(FyEnum.YPF.getName());
                    cntrInfo.setCntrWorkRemarkB(null);
                    cntrInfos.add(cntrInfo);
                    //cntrlog 发运箱动态信息
                    CntrLog log = new CntrLog();
                    BeanUtils.copyProperties(cntrInfo,log);
                    log.setCreatetime(LocalDateTime.now());
                    log.setAccesspath("PC");
                    cntrLogs.add(log);
                    //从业务cntr表获取专用线
                    String zyx = cntrMapper.getZyxByCntrNoAndOrderNo(cntrInfo.getCntrNo(),detail.getOrderNo());
                    BeanUtils.copyProperties(cntrInfo,detail);
                    //班列下集装箱详情的车牌号是装车理货的车皮号,不是箱子带来的车牌号
                    detail.setCarNo(null);
                    detail.setCreatetime(LocalDateTime.now());
                    detail.setUserName(user.getRealname());
                    detail.setAccesspath("PC");
                    detail.setArea(cntrInfo.getArea());
                    detail.setBay(cntrInfo.getBay());
                    detail.setGroupId(String.valueOf(millis));//分组时间戳id
                    detail.setLhWeight(cntrInfo.getLhWeight());//装车出场 理货\
                    detail.setPlanId(vo.getId());
                    if(cntrInfo.getCompanyId()!=null){
                        detail.setCompanyId(cntrInfo.getCompanyId().intValue());//货主 /客户id
                    }
                    detail.setLineOrYard(zyx);
                    trainPlanDetails.add(detail);
                }
            }else{
                TrainPlanDetail detail=list.get(0);
                //cntrinfo 发运箱动态信息
                CntrInfo cntrInfo = infoMapper.selectById(list.get(0));
                cntrInfo.setCntrWorkRemark(FyEnum.YPF.getName());
                cntrInfo.setCntrWorkRemarkB(null);
                cntrInfos.add(cntrInfo);
                //cntrlog 发运箱动态信息
                CntrLog log = new CntrLog();
                BeanUtils.copyProperties(cntrInfo,log);
                log.setCreatetime(LocalDateTime.now());
                log.setAccesspath("PC");
                cntrLogs.add(log);
                //从业务cntr表获取专用线
                String zyx = cntrMapper.getZyxByCntrNoAndOrderNo(cntrInfo.getCntrNo(),detail.getOrderNo());
                BeanUtils.copyProperties(cntrInfo,detail);
                //班列下集装箱详情的车牌号是装车理货的车皮号,不是箱子带来的车牌号
                detail.setCarNo(null);
                detail.setCreatetime(LocalDateTime.now());
                detail.setUserName(user.getRealname());
                detail.setAccesspath("PC");
                detail.setArea(cntrInfo.getArea());
                detail.setBay(cntrInfo.getBay());
                detail.setPlanId(vo.getId());
                detail.setGroupId(String.valueOf(millis));//分组时间戳id
                detail.setLhWeight(cntrInfo.getLhWeight());//装车出场 理货\
                if(cntrInfo.getCompanyId()!=null){
                    detail.setCompanyId(cntrInfo.getCompanyId().intValue());//货主 /客户id
                }
                detail.setLineOrYard(zyx);
                trainPlanDetails.add(detail);
            }
        }

        if(cntrInfos.size()>0){
            infoService.saveOrUpdateBatch(cntrInfos);
        }
        if(cntrLogs.size()>0){
            logService.saveBatch(cntrLogs);
        }
        if(trainPlanDetails.size()>0){
            b = saveBatch(trainPlanDetails);
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

}
